Component({
  mixins: [],
  data: {
    scrollTop: 0,
   
    threedate:'',
    threedates: '',
    fourdates: '',
    fivedates: '',
    datePrice: [],
    // 星期几,值为1-7
    weekday: 1,
    weekdayArr: [],
    // 当前月有多少天
    days: 0,
    daysArr: [],
    showTitle: '',
    year: 2020,
    month: 0,
    day: 0,
    startYear: 0,
    startMonth: 0,
    startDay: 0,
    startWeek: '',
    endYear: 0,
    endMonth: 0,
    endDay: 0,
    endWeek: '',
    today: '',
    activeDate: '',
    startDate: '',
    endDate: '',
    isStart: true,
    min: null,
    max: null,
    weekDayZh: ['日', '一', '二', '三', '四', '五', '六'],
    listData: [],
    startDateTime: "",//当前时间搓
    endDateTime: ""
  },
  props: {
    sum:{
      type: Number, //必填，目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）
      values: "" //可选，默认值，如果页面没传值过来就会使用默认值 
    },
    priceShow:{
      type: null, //必填，目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型） 
      value: "" //可选，默认值，如果页面没传值过来就会使用默认值 
    },
    // 通过双向绑定控制组件的弹出与收起
    value: false,
    // date-单个日期选择，range-开始日期+结束日期选择
    mode: 'range',
    // 日期选择标题
    title: '自定义租期',
    // 最小下单日期(不在范围内日期禁用不可选，包含当天)
    minDate: '',
    // 最大下单日期(不在范围内日期禁用不可选，包含当天)
    maxDate: '',
    // 是否禁止周六周日 不可下单 默认不禁止
    isWeekend: false,
    // 每天显示的提示
    altPrice: [{
      date: '2022-01-01',
      price: ''
    }],
    // 入住离开日期
    addOrRemoveData: []
  },
  didMount() {
    console.log("执行了111", this.props)
    this.data.timestamp = new Date().getTime();
    this.init()
  },
  didUpdate(a, b) {

    console.log("执行了444", this.props,)
    console.log("执行了222",a)
    console.log("执行了222",b)
    if(this.props.sum == ''){
      // this.init()
 
    
    }
    // if(a.mode!=b.mode|| a.minDate!=b.minDate||a.maxDate!=b.maxDate){
    //   this.init()
    // }
    //数据发生跟新的时候，重新获取入住和离店的时间错
    let startDateTime = this.data.startDate.replace(/\-/g, '/');
    let endDateTime = this.data.endDate.replace(/\-/g, '/');
    this.data.startDateTime = startDateTime;
    this.data.endDateTime = endDateTime;

  },
  deriveDataFromProps(nextProps) {
    if (JSON.stringify(this.data.itemData) !== JSON.stringify(this.data.itemData)) {
      //业务处理
      this.init()
 
    }
  },
  


  didUnmount() { console.log("组件初始化111");},
  methods: {
    init() {
      /// 初始化日期
      let threedate = this.getDateStr(3)
      console.log("556++++++++++++++", this.props)
      let now = new Date();
      this.setData({

        // 初始化日期下的 文字
        threedate: threedate,
        datePrice: this.props.altPrice,
        year: now.getFullYear(),
        month: now.getMonth() + 1,
        day: now.getDate(),
        today: `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`,
        activeDate: this.props.today,
        min: this.initDate(this.props.minDate),
        max: this.initDate(this.props.maxDate || this.props.today),
        startDate: "",
        startWeek: "",
        startYear: 0,
        startMonth: 0,
        startDay: 0,
        endYear: 0,
        endMonth: 0,
        endDay: 0,
        endDate: "",
        endWeek: "",
        isStart: true,
        listData: [],
        selectList: []
      })
    
      this.changeData();
      // 默认显示两个月
      let _this = this
      setTimeout(() => {
        _this.changeMonthHandler(1)
      }, 100)

      setTimeout(() => {
        _this.changeMonthHandler(1)
      }, 2000);
      // 初始化入住离店时间
      if (this.props.addOrRemoveData.length > 0) {
        setTimeout(() => {
          _this.addOrRemoveChange()
        }, 200)
      }
    },
   getDateStr(addDayCount) {
  var dd;


    dd = new Date();

  dd.setDate(dd.getDate() + addDayCount);//获取AddDayCount天后的日期 
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;//获取当前月份的日期 
  var d = dd.getDate();
  if(m < 10) {
    m = '0' + m;
  };
  if(d < 10) {
    d = '0' + d;
  };
  return y + "-" + m + "-" + d;
},
    //日期处理
    initDate(date) {
      console.log("=====",date)
     
      let fdate = date.split('-');
      console.log("55+", fdate)
      return {
        year: Number(fdate[0] || 2022),
        month: Number(fdate[1] || 1),
        day: Number(fdate[2] || 1)
      }
    
    },
    // 判断可使用日期范围
    openDisAbled(year, month, day) {

      let bool = true;
      let date = `${year}/${month}/${day}`;
      let today = this.data.today.replace(/\-/g, '/');
      let min = `${this.data.min.year}/${this.data.min.month}/${this.data.min.day}`;
      let max = `${this.data.max.year}/${this.data.max.month}/${this.data.max.day}`;
      let timestamp = new Date(date).getTime();
      console.log("22+",min, max)
      if (timestamp < new Date(min).getTime() || timestamp > new Date(max).getTime()) {
        bool = false;
        my.showToast({ content: "选择时间超出范围" })
        console.log('选择时间超出范围')
      }
      // 判断是否大于今日
      if (timestamp < new Date(today).getTime()) {
        console.log("选择时间不能小于当前时间")
        bool = false;
      }

      // 禁止周六周日下单
      if (this.isWeekend && (this.getWeekText(date) === '星期六' || this.getWeekText(date) === '星期日')) {
        bool = false;
      }



      return bool;
    },
    // 判断是否再选中日期范围内
    openStartOrend(year, month, day) {
      let bool = false;
      let date = `${year}/${month}/${day}`;
      let startDate = this.data.startDate.replace(/\-/g, '/');
      let endDate = this.data.endDate.replace(/\-/g, '/');
      let timestamp = new Date(date).getTime();

      if (timestamp > new Date(startDate).getTime() && timestamp < new Date(endDate).getTime()) {
        bool = true
      }

      return bool
    },
    // 显示日期下的文字提示
    viewDayAlt(year, month, day) {
      console.log("显示日期下的文字提示")
      let txt = ''
      let item = this.data.datePrice.find(item => {
        let today = item.date.replace(/\-/g, '/');
        let date = `${year}/${month}/${day}`;
        return new Date(date).getTime() === new Date(today).getTime()
      })
      if (item) {
        return Number.isFinite(item.price) ? '￥' + item.price : item.price
      }
    },
    generateArray(start, end) {
      return Array.from(new Array(end + 1).keys()).slice(start);
    },
    formatNum(num) {
      return num < 10 ? '0' + num : num + '';
    },
    //一个月有多少天
    getMonthDay(year, month) {
      let days = new Date(year, month, 0).getDate();
      return days;
    },
    getWeekday(year, month) {
      let date = new Date(`${year}/${month}/01 00:00:00`);
      return date.getDay();
    },
    checkRange(year) {
      let overstep = false;
      if (year < this.minYear || year > this.maxYear) {
        my.showToast({
          title: "日期超出范围啦~",
          icon: 'none'
        })
        overstep = true;
      }
      return overstep;
    },
    //scorllview触底
    changeMonthHandler(isAdd) {
      console.log(isAdd, "isAddisAddisAdd")
      if (isAdd) {
        // 根据日期限制显示
        if (this.data.year >= this.data.max.year && this.data.month >= this.data.max.month) {
          console.log(false)
          return false
        }

        let month = this.data.month + 1;
        let year = month > 12 ? this.data.year + 1 : this.data.year;
        if (!this.checkRange(year)) {
          console.log("checkRangecheckRange")
          this.data.month = month > 12 ? 1 : month;
          this.data.year = year;
          this.changeData();
        }

      } else {
        let month = this.month - 1;
        let year = month < 1 ? this.year - 1 : this.year;
        if (!this.checkRange(year)) {
          console.log("checkRangecheckRangeerrrrrr")
          this.data.month = month < 1 ? 12 : month;
          this.data.year = year;
          this.changeData();
        }
      }
    },
    changeYearHandler(isAdd) {
      let year = isAdd ? this.year + 1 : this.year - 1;
      if (!this.checkRange(year)) {
        this.data.year = year;
        this.changeData();
      }
    },
    changeData() {
      this.data.days = this.getMonthDay(this.data.year, this.data.month);
      this.data.daysArr = this.generateArray(1, this.data.days)
      this.data.weekday = this.getWeekday(this.data.year, this.data.month);
      this.data.weekdayArr = this.generateArray(1, this.data.weekday)
      this.data.showTitle = `${this.data.year}年${this.data.month}月`;
      if (this.data.isChange && this.data.mode == 'date') {
        this.btnFix(true);
      }
      this.setDayText()
    },
    // 处理插入数据时间列表
    setDayText() {
      console.log("插入数==", this.data.listData)
      let daysArr = this.data.daysArr;
      let year = this.data.year;
      let month = this.data.month;
      let newDaysBoolArr = [];//控制颜色
      let showBoolArr = [];//控制是否可点击
      daysArr.map(item => {
        let day = item > 9 ? item : "0" + item;
        showBoolArr.push(this.openDisAbledBool(year, month, day))
        newDaysBoolArr.push(false)
      })
      let listData = this.data.listData;
      listData.push({
        year: this.data.year,
        month: this.data.month,
        weekdayArr: this.data.weekdayArr,
        daysArr: this.data.daysArr,
        showTitle: this.data.showTitle,
        newDaysBoolArr: newDaysBoolArr,
        showBoolArr: showBoolArr
      })

      this.setData({
        listData
      })

    },
    //判断日期是否为不可点击
    openDisAbledBool(year, month, day) {
      let bool = true;
      let date = `${year}/${month}/${day}`;
      let timestamp = new Date(date).getTime();
      let today = this.data.today.replace(/\-/g, '/');
      if (timestamp < new Date(today).getTime()) {
        bool = false;
      }
      return bool;
    },
    // 处理初始化入住离店时间
    addOrRemoveChange() {
      let _this = this
      this.addOrRemoveData.forEach((item, index) => {
        let data = item.replace(/\-/g, '/')
        let now = new Date(data);
        let year = now.getFullYear();
        let month = now.getMonth() + 1;
        let day = now.getDate() - 1;

        if (index === 0) {
          this.dateClick({ year: year, month: month }, day)
        } else {
          setTimeout(() => {
            _this.dateClick({ year: year, month: month }, day)
          }, 300)
        }
      })
    },
    // 选择日期操作
    dateClick(evt) {
      console.log("111",evt)
      let { item, index: day, showbool } = evt.target.dataset;
      let listData = this.data.listData;
      if (!showbool) return false;

      // item, day
      day += 1;
      if (this.openDisAbled(item.year, item.month, day)) {

        this.data.day = day;
        let date = `${item.year}-${item.month}-${day}`;
        console.log("999999+", date)
        if (this.data.mode == 'date') {
          console.log("只选择一个时间")
          this.data.activeDate = date;
          this.btnFix(true)
        } else {
          console.log("选择开始和离店2个时间")
          let compare = new Date(date.replace(/\-/g, '/')).getTime() < new Date(this.data.startDate.replace(/\-/g, '/')).getTime()



          if (this.data.isStart || compare) {

            console.log("选择开始时间", date)
            let fourdates = this.getDateStrs(date, -1)
            let fivedates = this.getDateStrs(date, -2)
            console.log("/////", fourdates)
            this.setData({
              threedates:'',
              fourdates: fourdates,
              fivedates: fivedates,
              startDate: date,
              listData,
              startYear: item.year,
              startMonth: item.month,
              startDay: day,
              endYear: 0,
              endMonth: 0,
              endDay: 0,
              endDate: "",
              activeDate: "",
              startWeek: this.getWeekText(date),
              isStart: false,
              datePrice: [{
                date: date,
                price: '入住'
              }]
            })
            //删除选择区域
            this.resetListData(listData, 2)

          } else {
             
            console.log("选择离店时间",date)
         
            let dates = this.DateDiff(date, this.data.startDate)
            console.log("99+--", dates)
            if (Number(dates + 1) < 30) {


              my.showToast({
                type: 'exception ',
                content: '起租时间为30天,已自动为你补齐！',
                duration: 2000,
              });
              let datess = this.getDateStrs(this.data.startDate, 29)
              console.log("1115654646", datess)
              let newtate = datess.split(/[\s:-]/)

              console.log("1115654646", newtate)

              let threedates = this.getDateStrs(datess, 1)
              console.log("112323+++++++", newtate[2] - 1)
              this.setData({
                threedates: threedates,
                endDate: datess,
                endYear: newtate[0],
                endMonth: newtate[1],
                endDay: newtate[2],
                endWeek: this.getWeekText(datess),
                isStart: true,
                datePrice: this.data.datePrice.push({
                  date: datess,
                  price: '离开'
                })
              })
            }else{
              console.log("选择离店时间", date)
              let threedates = this.getDateStrs(date, 1)
              console.log("112323", threedates, date)
              this.setData({
                threedates: threedates,
                endDate: date,
                endYear: item.year,
                endMonth: item.month,
                endDay: day,
                endWeek: this.getWeekText(date),
                isStart: true,
                datePrice: this.data.datePrice.push({
                  date: date,
                  price: '离开'
                })
              })
            }
           
            //设置选择区域
            this.resetListData(listData, 1)

            //是否手动关闭时间组件并返回数据
            this.btnFix(true)
          }

        }
      }
    },
    DateDiff(sDate1, sDate2) {
      //sDate1和sDate2是年-月-日格式
      var arrDate, objDate1, objDate2, intDays;
      arrDate = sDate1.split("-");
      objDate1 = new Date(arrDate[1] + '-' + arrDate[2] + '-' + arrDate[0]);//转换为月-日-年格式
      arrDate = sDate2.split("-");
      objDate2 = new Date(arrDate[1] + '-' + arrDate[2] + '-' + arrDate[0]);
      intDays = parseInt(Math.abs(objDate1 - objDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
      return intDays;
    },
     getDateStrs(today, addDayCount) {
  var dd;
  if(today) {
    dd = new Date(today);
  }else{
    dd = new Date();
  }
  dd.setDate(dd.getDate() + addDayCount);//获取AddDayCount天后的日期 
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;//获取当前月份的日期 
  var d = dd.getDate();
  if(m < 10) {
    m = m;
  };
  if(d < 10) {
    d =  d;
  };
  return y + "-" + m + "-" + d;
},
    //设置选择区域颜色
    resetListData(listData, type) {
      
      listData.forEach((firstItem, firstIndex) => {
        if (type == 2) {
          firstItem.newDaysBoolArr.forEach((subItem, subindex) => {
            listData[firstIndex].newDaysBoolArr[subindex] = false;
          })
        } else {


          firstItem.daysArr.forEach((subItem, subindex) => {

            if (this.openStartOrend(firstItem.year, firstItem.month, subItem)) {
              listData[firstIndex].newDaysBoolArr[subindex] = true;
            }
          })
        }


      })
      console.log("6666666", listData, this.data.priceshow)
      this.setData({
        listData: listData
      })
    },


    close() {
      this.data.scrollTop = 0
      // 修改绑定的父组件变量的值为false，从而隐藏日历弹窗
      this.props.onCloseFunc(false);
    },
    getWeekText(date) {
      date = new Date(`${date.replace(/\-/g, '/')} 00:00:00`);
      let week = date.getDay();
      return '星期' + ['日', '一', '二', '三', '四', '五', '六'][week];
    },
    btnFix(show) {
      if (!show) {
        this.close();
      }
      if (this.data.mode == 'date') {
        let arr = this.data.activeDate.split('-')
        let year = this.data.isChange ? this.data.year : Number(arr[0]);
        let month = this.data.isChange ? this.data.month : Number(arr[1]);
        let day = this.data.isChange ? this.data.day : Number(arr[2]);
        //当前月有多少天
        let days = this.getMonthDay(year, month);
        let result = `${year}-${this.formatNum(month)}-${this.formatNum(day)}`;
        let weekText = this.getWeekText(result);
        let isToday = false;
        if (`${year}-${month}-${day}` == this.data.today) {
          //今天
          isToday = true;
        }
        this.props.onTurnMsg({
          year: year,
          month: month,
          day: day,
          days: days,
          activeDate: this.data.activeDate,
          result: result,
          week: weekText,
          isToday: isToday
        });
      } else {
        if (!this.data.startDate || !this.data.endDate) return;
        let startMonth = this.formatNum(this.data.startMonth);
        let startDay = this.formatNum(this.data.startDay);
        let startDate = `${this.data.startYear}-${startMonth}-${startDay}`;
        let startWeek = this.getWeekText(startDate)

        let endMonth = this.formatNum(this.data.endMonth);
        let endDay = this.formatNum(this.data.endDay);
        let endDate = `${this.data.endYear}-${endMonth}-${endDay}`;
        let endWeek = this.getWeekText(endDate);
        this.props.onTurnMsg({
          startYear: this.data.startYear,
          startMonth: this.data.startMonth,
          startDay: this.data.startDay,
          startDate: startDate,
          startWeek: startWeek,
          endYear: this.data.endYear,
          endMonth: this.data.endMonth,
          endDay: this.data.endDay,
          endDate: endDate,
          endWeek: endWeek
        })
      }
    }
  },
});